.globl  BinAsc, AscBin

; void BinAsc(unsigned long D, char * S)

BinAsc:
        st      -Y,r27
        st      -Y,r26
        st      -Y,r25
        st      -Y,r24
        st      -Y,r4
        movw    r30,r20
        
        clr     r0
        clr     r1
        clr     r2
        clr     r3
        clr     r4
	ldi 	r20,32

prn1:
        ldi     r26,0
        clr     r27
	ldi 	r21,5
prn2:
	ldi 	r25,0x33
	ld  	r24,X
	add 	r24,r25
	sbrc 	r24,7
	andi	r25,0x0F
	sbrc	r24,3
	andi	r25,0xF0
	sub 	r24,r25
	st  	X+,r24
	dec 	r21
	brne	prn2
	
        lsl     r16
        rol     r17
        rol     r18
        rol     r19
        rol     r0
        rol     r1
        rol     r2
        rol     r3
        rol     r4
        dec     r20
        brne    prn1
        
        clt
        ldi     r26,5
        clr     r27
prn3:
        ld      r24,-X
        rcall   prn5
        cpi     r26,1
	brsh 	prn3
	brts	prn4
	set
	mov 	r24,r0
	rcall	prn6
prn4:
        ldi     r24,0
        st      Z,r24
        ld      r4,Y+
        ld     r24,Y+
        ld     r25,Y+
        ld     r26,Y+
        ld     r27,Y+
	ret       
	
prn5:
	push 	r24
	swap	r24
	rcall	prn6
	pop  	r24
prn6:
	andi	r24,0x0f	; convert to ASCII and eliminate leading zeros
	subi	r24,-'0'
	brts	putchar
	cpi 	r24,'0'
	brne	prn7
	; if you want leading spaces for nice format, uncomment below
	; ldi r24, ' ' 
	; rjmp putchar
	ret
prn7:
	set
putchar:
        st      Z+,r24
        ret
	
; unsigned long AscBin(char * S)

AscBin:
	st	-Y,r4
	st	-Y,r27
	st	-Y,r26
	st	-Y,r25
	st	-Y,r24
	movw	r2,r16

	ldi	R16,1
	clr	R17
	clr	R18
	clr	R19
	clr	R20
	clr	R21
	clr	R22
	clr	R23

	movw	R30,R2
	rjmp	a1
a2:
	adiw	R30,1
a1:
	ld	R0,Z
	tst	R0
	brne	a2
a3:
	ld	R24,-Z
	ldi	R25,0
	sbiw	R24,48
	mov	R26,R25
	lsl	R26
	sbc	R26,R26
	mov	R27,R26
	clr	R4
	rcall	mul10
	add	R25,R1
	adc	R26,R4
	adc	R27,R4
	add	R20,R0
	adc	R21,R25
	adc	R22,R26
	adc	R23,R27
	ldi	R24,10
	clr	R25
	clr	R26
	clr	R27
	RCALL	mul10
	mov	R24,R0
	add	R25,R1
	adc	R26,R4
	adc	R27,R4
	movw	R16,R24
	movw	R18,R26
	cp	R2,R30
	cpc	R3,R31
	brcs	a3

	movw	R16,R20
	movw	R18,R22
	ld	R24,Y+
	ld	R25,Y+
	ld	R26,Y+
	ld	R27,Y+
	ld	R4,Y+
	ret

mul10:
	MUL	R27,R16
	MOV	R27,R0
	MUL	R26,R17
	ADD	R27,R0
	MUL	R25,R18
	ADD	R27,R0
	MUL	R24,R19
	ADD	R27,R0
	MUL	R26,R16
	MOV	R26,R0
	ADD	R27,R1
	MUL	R25,R17
	ADD	R26,R0
	ADC	R27,R1
	MUL	R24,R18
	ADD	R26,R0
	ADC	R27,R1
	MUL	R25,R16
	MOV	R25,R0
	ADD	R26,R1
	ADC	R27,R4
	MUL	R24,R17
	ADD	R25,R0
	ADC	R26,R1
	ADC	R27,R4
	MUL	R24,R16
	RET
